/*
create by 2021-1-4 全屏播放互动课件页面
*/
$(function () {
    let video = $("#video");
    let source = $("#video source")
    let isScreen = false;
    let player = $("#player");
    let Timeout = null; // 移入隐藏显示控制台定时器
    let isComponentShow = false; //用来判断是否处于组件显示阶段，如果是则点击播放暂停视频事件不能使用
    /**
     * 头部logo加载对应机构
     */
    let userinfo = extendLocalStorage.get("userinfo");
    let curOrgan = extendLocalStorage.get("curOrgan");
    if (curOrgan) {
        $(".Hleft a:nth-child(1)").empty();
        $(".Hleft a:nth-child(1)").append(`<p style="width: 100%;" id="logoText" org_id=${curOrgan.org_id}>${curOrgan.name}</p>`);
    }
    /**
     * 头部logo加载对应机构
     */
    // 禁止右击事件，因为video的右击事件会有显示控制台
    player.contextmenu(function (e) {
        e.preventDefault()
    });
    // 点击video播放/暂停视频
    video.click(function (e) {
        e.preventDefault();
        if (video[0].paused && !isComponentShow) {
            video[0].play();
            $("#isPause").hide();
        } else {
            video[0].pause();
            $("#isPause").show();
        }
        return false;
    });

    function playermouseenter() {
        $("#videoControls").show();
        player.mousemove(function (e) {
            clearTimeout(Timeout);
            Timeout = setTimeout(() => {
                $("#videoControls").hide();
            }, 2000);
            $("#videoControls").show();
        });
        // 移入video 添加键盘的快进后退
        $(document).keydown(function (event) {
            //判断当event.keyCode 为37时（即左方面键），执行函数to_left();
            //判断当event.keyCode 为39时（即右方面键），执行函数to_right();
            $("#orPlay img").attr("src", "./images/bofang.png");
            if (event.keyCode === 37 && !isComponentShow) {
                $("#videoControls").show();
                video[0].currentTime -= 5;
                video[0].play();
            } else if (event.keyCode === 39 && !isComponentShow) {
                $("#videoControls").show();
                video[0].currentTime += 5;
                video[0].play();
            }
        });
    }

    function playermouseleave() {
        $(document).unbind(); //移除video解绑此事件
        setTimeout(() => {
            $("#videoControls").hide();
        }, 2000);
    }
    player.mouseenter(playermouseenter);
    player.mouseleave(playermouseleave);
    // 进入全屏兼容函数
    function requestFullscreen(ele) {
        // 全屏兼容代码  js方法不是jq的
        if (ele.requestFullscreen) {
            ele.requestFullscreen();
        } else if (ele.webkitRequestFullscreen) {
            ele.webkitRequestFullscreen();
        } else if (ele.mozRequestFullScreen) {
            ele.mozRequestFullScreen();
        } else if (ele.msRequestFullscreen) {
            ele.msRequestFullscreen();
        }
        $("#selComponent p").css({
            "line-height": "4.5rem",
            "font-size": "1.8rem"
        })
    }
    // 取消全屏兼容函数
    function exitFullscreen() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        }
        $("#selComponent p").css({
            "line-height": "2.5rem",
            "font-size": "1rem"
        })
    }
    // 全屏按钮事件
    $("#fullScreen").click(function (e) {
        e.preventDefault();
        if (isScreen == false) {
            requestFullscreen(player[0]);
            isScreen = true;
        } else {
            exitFullscreen(player[0]);
            isScreen = false;
        }
    });
    // enter 进入全屏
    $(window).keydown(function (e) {
        // console.log(e.keyCode); //13为enter
        if (e.keyCode == 13) {
            isScreen ? exitFullscreen(player[0]) : requestFullscreen(player[0]);
            isScreen = !isScreen;
        }
    });
    //时间格式化  00 ： 00            
    function timer(seconds) {
        var minute = Math.floor(seconds / 60);
        if (minute < 10) {
            minute = "0" + minute;
        }
        var second = Math.floor(seconds % 60);
        if (second < 10) {
            second = "0" + second;
        }
        return minute + ":" + second;
    }
    // 视频加载后，获取视频长度赋值给总时间
    video.on('loadedmetadata', function () {
        console.log("视频总时长：" + video[0].duration);
        // 视频刚加载出画面后
        $('#endTime').text(timer(video[0].duration));
    });
    // 视频现在时间每更新一次，就对应更新currenTime
    video.on('timeupdate', function () {
        var currentTime = video[0].currentTime;
        var duration = video[0].duration;
        var percent = currentTime / duration * 100;
        $("#progress div").css("width", percent + "%");
        $("#progress div span").css("left", "99%");
        $('#currenTime').text(timer(currentTime));
        if (currentTime >= duration) { //当播放到暂停时，将播放停止图标改过来
            $("#orPlay img").attr("src", "./images/zanting.png");
        }
    });
    $("#progress").click(function (e) {
        e.preventDefault();
        let totalWid = $(this).width();
        let clickWid = e.offsetX;
        let precent = clickWid / totalWid * 100;
        video[0].currentTime = precent / 100 * video[0].duration;
        $("#progress div").css("width", precent + "%");
        video[0].play(); //每次点击快进都会播放
        $("#isPause").hide();
        $("#orPlay img").attr("src", "./images/bofang.png");
    });

    // 进度条上方切换分支视频
    $("#cliVideo ").on('mouseenter', 'img', function () {
        if ($(this).hasClass("curVideo")) {
            $(this).attr("src", "./images/fullscreenVIdeo/Hoverdingwei.png")
            return false;
        }
        $(this).attr("src", "./images/fullscreenVIdeo/Hoverfenzhi.png")

    });
    $("#cliVideo").on('mouseleave', 'img', function () {
        if ($(this).hasClass("curVideo")) {
            $(this).attr("src", "./images/fullscreenVIdeo/dingwei.png")
            return false;
        }
        $(this).attr("src", "./images/fullscreenVIdeo/fenzhi.png")
    });
    /*
    互动课件开始
    */
    let data = {};
    let locationInfo = location.href; //点击互动视频封面传过来的id参数，用来调用此互动视频获取信息接口
    interactCouId = locationInfo.slice(locationInfo.indexOf("=") + 1, locationInfo.indexOf("&"));
    let isbei = locationInfo.split("isbei=")[1]; //是否有备课教案 1有 0无
    // console.log(interactCouId,isbei); 
    let courseData = {
        id: interactCouId
    }
    $.ajax({
        type: "get",
        url: `${testUrl}/platform/resource/view`,
        headers: {
            token: userinfo.token
        },
        data: courseData,
        success: function (res) {
            if (res.code == 0) {
                alert("此互动视频数据异常");
                location.href = './index.html'
            }
            $(".personal strong").text(res.data.title); //根据互动视频名称修改头部logo后的名称
            data = res.data.context;
            $("#cliVideo").on('click', 'img', function () {
                if ($(this).hasClass("curVideo")) { //如果是当前视频图标则点击不起作用
                    return false;
                }
                // //使被点击的树叉变成正在播放的图标
                // $("#cliVideo img").attr("src", "./images/fullscreenVIdeo/fenzhi.png").removeClass("curVideo");
                // $(this).attr("src", "./images/fullscreenVIdeo/dingwei.png").addClass("curVideo");
                // 使组件的数据变回点击的数据
                let cliIndex = $(this).index();
                let dataInfo = cacheArrInfo[cliIndex];
                video.attr("src", dataInfo.playUrl);
                cacheArrInfo = cacheArrInfo.slice(0, cliIndex + 1); //将其之后的数组项删除掉
                $("#cliVideo").empty();
                $.each(cacheArrInfo, function (i, item) {
                    $("#cliVideo").append(`<img playUrl=${dataInfo.playUrl} src="./images/fullscreenVIdeo/fenzhi.png">`);
                });
                $("#cliVideo img:last-child").attr("src", "./images/fullscreenVIdeo/dingwei.png").addClass("curVideo");
                defaultOption = dataInfo.defaultOption; //默认选项 树叉上的字段
                children = dataInfo.children; //树叉下的分支
                pictureStop = dataInfo.pictureStop; //是否有画面暂停组件
                noComponent = dataInfo.noComponent;
                TPplayUrl = dataInfo.TPplayUrl;
                // 使组件的数据变回点击的数据  结束
            });
            // 先加载根视频
            video.attr("src", data.playUrl);
            $("#cliVideo").append(`<img playUrl=${data.playUrl} class="curVideo" src="./images/fullscreenVIdeo/dingwei.png">`);
            let cacheArrInfo = []; //其存入的每条数据下标对应剧情树的每一块
            let defaultOption = data.defaultOption; //默认选项 树叉上的字段
            let children = data.children; //树叉下的分支
            let pictureStop = data.pictureStop; //是否有画面暂停组件
            let noComponent = data.noComponent; //无组件直接播放下分支
            let TPplayUrl = data.TPplayUrl;
            let labelInfo = data.labelInfo; //标注信息
            let selSum = $("#selComponent p"); //所有的选项p
            let defaultOptionTimer = null;
            cacheArrInfo.push(data)
            video.unbind('play').bind('play', function () {
                // console.log("开始")  ; //开始播放时会将选项全部隐藏
                selSum.css("display", "none");
                isComponentShow = false;
                $("#videoControls").css("display", 'block'); //暂停选择下一分支时，将视频控件删除（隐藏实现不了，所以只能删除属性）
                $("#orPlay img").attr("src", "./images/bofang.png");
                if (isbei == 0) {
                    return false;
                }
                if (TPplayUrl) {
                    $("#teachVideo").css("display", "block");
                    $("#teachVideo").attr("src", TPplayUrl);
                } else {
                    $("#teachVideo").css("display", "none");
                    $("#teachVideo").trigger("pause");
                }
            })
            video.unbind('pause').bind('pause', function () {
                $("#orPlay img").attr("src", "./images/zanting.png");
            })
            video.unbind('ended').bind('ended', function () {
                player.unbind(); //视频暂停组件弹出后，移入移除显示控制台事件解绑
                // $(document).unbind();
                if (!children || children.length === 0) {
                    console.log("视频播放结束且当前视频后已无分支视频");
                    $("#videoControls").css("display", 'block'); //暂停选择下一分支时，将视频控件删除（隐藏实现不了，所以只能删除属性）
                    return false;
                }
                this.currentTime = this.duration - 3;
                isComponentShow = true;
                $("#videoControls").css("display", 'none'); //暂停选择下一分支时，将视频控件删除（隐藏实现不了，所以只能删除属性）
                /**
                 * 无组件且只有一个分支时，则自动播放下个视频
                 */
                // console.log(info.defaultOption, !info.defaultOption);
                // console.log(info.pictureStop, !info.pictureStop);
                // console.log(bool, !bool);
                if (noComponent) {
                    // console.log("无组件且只有一个分支时，则自动播放下个视频");
                    let dataInfo = children[0];
                    let playUrl = children[0].playUrl;
                    pictureStop = children[0].pictureStop;
                    defaultOption = children[0].defaultOption; //因为代码进行到这里证明播放下个分支视频了，所以需要将倒计时进行重新赋值，赋值为要播放分支得defaultOption
                    noComponent = children[0].noComponent;
                    TPplayUrl = children[0].TPplayUrl;
                    children[0].labelInfo ? labelInfo = children[0].labelInfo : labelInfo = "";
                    children = children[0].children;
                    video.attr("src", playUrl);
                    passVideo(dataInfo);
                    return false
                }
                /**
                 * 无组件且只有一个分支时，则自动播放下个视频  ------结束
                 */
                /**
                 * 标注组件 直接播放下个分支 
                 */
                console.log(labelInfo);
                if (labelInfo) { //labelComponent
                    $("#labelComponent .setLbel").remove();
                    let clickNum = 0;
                    let zimu = "";
                    $("#labelComponent img").attr("src",labelInfo.labelBackgroundImg);
                    for (let i = 0; i < labelInfo.num; i++) {
                        if (i == 0) {
                            zimu = "A";
                        } else if (i == 1) {
                            zimu = "B";
                        } else if (i == 2) {
                            zimu = "C";
                        } else if (i == 3) {
                            zimu = "D";
                        }
                        $("#labelComponent").append(`
                        <div class="setLbel label${zimu}" style="left:${labelInfo.x[i]};top:${labelInfo.y[i]};transform:rotate(${labelInfo.rotate[i]}deg)">
                        <em class="iconfont icondian"></em>
                        <i></i>
                            <p>${labelInfo.textInfo[i]}</p>
                        </div>
                        `)
                    }
                    $("#labelComponent").css("display", "block")
                    video.css({
                        display: "none"
                    })
                    $("#labelComponent").unbind("click").click(function (e) {
                        e.preventDefault();
                        if (clickNum >= 5) { //大于5 跳下个分支
                            let playUrl = children[0].playUrl;
                            pictureStop = children[0].pictureStop;
                            defaultOption = children[0].defaultOption; //因为代码进行到这里证明播放下个分支视频了，所以需要将倒计时进行重新赋值，赋值为要播放分支得defaultOption
                            noComponent = children[0].noComponent;
                            TPplayUrl = children[0].TPplayUrl;
                            children[0].labelInfo ? labelInfo = children[0].labelInfo : labelInfo = "";
                            console.log("标注组件" + labelInfo);
                            children = children[0].children;
                            $(this).css("display", "none");
                            video.css("display", "block");
                            video.attr("src", playUrl);
                        }
                        clickNum++;
                    });
                    return false;
                }
                /**
                 * 标注组件 直接播放下个分支 结束
                 */
                // 画面暂停组件
                if (pictureStop == 1) {
                    $("#picStopBtn").css("display", "block");
                    $("#picStopBtn").unbind("click").bind("click", function () {
                        $("#picStopBtn").css("display", "none");
                        let dataInfo = children[0];
                        let playUrl = children[0].playUrl;
                        pictureStop = children[0].pictureStop;
                        defaultOption = children[0].defaultOption; //因为代码进行到这里证明播放下个分支视频了，所以需要将倒计时进行重新赋值，赋值为要播放分支得defaultOption
                        noComponent = children[0].noComponent;
                        TPplayUrl = children[0].TPplayUrl;
                        children[0].labelInfo ? labelInfo = children[0].labelInfo : labelInfo = "";
                        children = children[0].children;
                        video.attr("src", playUrl);
                        passVideo(dataInfo);
                    })
                    return false;
                }


                // 视频结束，判断加载选项个数
                if (children.length === 1) {
                    $("#selComponent #preSelA").css({
                        left: "27.5%",
                        bottom: '12%'
                    });
                    $("#preSelA").css("display", "block").text(children[0].answerName).attr("treeId", children[0].id);
                } else if (children.length === 2) {
                    selSum.css({
                        width: "40%"
                    });
                    $("#selComponent #preSelA").css({
                        bottom: '12%',
                        left: "7%"
                    });
                    $("#selComponent #preSelB").css({
                        bottom: '12%',
                        left: "52%"
                    });
                    $("#preSelA").css("display", "block").text(children[0].answerName).attr("treeId", children[0].id);
                    $("#preSelB").css("display", "block").text(children[1].answerName).attr("treeId", children[1].id);
                } else if (children.length === 3) {
                    selSum.css({
                        width: "25%"
                    });
                    $("#selComponent #preSelA").css({
                        left: "7%",
                        bottom: '12%'
                    });
                    $("#selComponent #preSelB").css({
                        left: "37%",
                        bottom: '12%'
                    });
                    $("#selComponent #preSelC").css({
                        left: "67%",
                        bottom: '12%'
                    });
                    $("#preSelA").css("display", "block").text(children[0].answerName).attr("treeId", children[0].id);
                    $("#preSelB").css("display", "block").text(children[1].answerName).attr("treeId", children[1].id);
                    $("#preSelC").css("display", "block").text(children[2].answerName).attr("treeId", children[2].id);
                } else if (children.length === 4) {
                    selSum.css({
                        width: "40%"
                    });
                    $("#selComponent #preSelA").css({
                        left: "7%",
                        bottom: '24%'
                    });
                    $("#selComponent #preSelB").css({
                        left: "52%",
                        bottom: '24%'
                    });
                    $("#selComponent #preSelC").css({
                        bottom: '12%',
                        left: "7%"
                    });
                    $("#selComponent #preSelD").css({
                        bottom: '12%',
                        left: "52%"
                    });
                    $("#preSelA").css("display", "block").text(children[0].answerName).attr("treeId", children[0].id);
                    $("#preSelB").css("display", "block").text(children[1].answerName).attr("treeId", children[1].id);
                    $("#preSelC").css("display", "block").text(children[2].answerName).attr("treeId", children[2].id);
                    $("#preSelD").css("display", "block").text(children[3].answerName).attr("treeId", children[3].id);
                }
                //倒计时默认选项组件
                if (defaultOption) {
                    console.log("倒计时默认选项开始了");
                    defaultOptionTimer = setTimeout(() => {
                        selSum.css("display", "none");
                        //点击某一个选项时，获取这个选项的上的treeId，用此字段去调用G6的方法，查找其树叉的数据信息
                        let dataInfo = getTreeId(children, defaultOption); //g6api  通过数据中某一个数据的id 过去数据本身
                        console.log(dataInfo);
                        defaultOption = dataInfo.defaultOption; //将播放的树叉的默认选项字段加给他
                        pictureStop = dataInfo.pictureStop;
                        noComponent = dataInfo.noComponent;
                        dataInfo.labelInfo ? labelInfo = dataInfo.labelInfo : labelInfo = "";
                        TPplayUrl = dataInfo.TPplayUrl;
                        children = dataInfo.children;
                        // console.log(children);
                        video.attr("src", dataInfo.playUrl);
                        passVideo(dataInfo);
                    }, 5000);
                }

                // 选项卡点击组件
                selSum.unbind("click").click(function (e) {
                    e.preventDefault();
                    clearTimeout(defaultOptionTimer);
                    selSum.css("display", "none");
                    //点击某一个选项时，获取这个选项的上的treeId，用此字段去调用G6的方法，查找其树叉的数据信息
                    let treeId = $(this).attr("treeId");
                    let dataInfo = getTreeId(children, treeId);
                    pictureStop = dataInfo.pictureStop;
                    defaultOption = dataInfo.defaultOption; //将播放的树叉的默认选项字段加给他
                    noComponent = dataInfo.noComponent; //将播放的树叉的默认选项字段加给他
                    TPplayUrl = dataInfo.TPplayUrl;
                    dataInfo.labelInfo ? labelInfo = dataInfo.labelInfo : labelInfo = "";
                    children = dataInfo.children;
                    video.attr("src", dataInfo.playUrl);
                    passVideo(dataInfo);
                });
            })
            // 用来替代g6引擎通过id获取数据的方法
            function getTreeId(children, id) {
                let result = children.filter((item, i) => {
                    return item.id === id
                })
                return result[0];
            }
            // 用户经历的剧情分支
            function passVideo(dataInfo) {
                // 播放下个分支给player添加事件
                player.mouseenter(playermouseenter);
                player.mouseleave(playermouseleave);
                cacheArrInfo.push(dataInfo);
                $("#cliVideo img").attr("src", "./images/fullscreenVIdeo/fenzhi.png").removeClass("curVideo");
                $("#cliVideo").append(`<img playUrl=${dataInfo.playUrl} class="curVideo" src="./images/fullscreenVIdeo/dingwei.png">`);
                let trees = $("#cliVideo img");
                // $($("#cliVideo img")[trees.length - 2]).attr("title", "选择的是：" + dataInfo.answerName);
                video[0].play();
            }
        }
    });
    /*
    互动课件结束
    */
    /**
     * 备课教案视频
     */
    $("#teachVideo").unbind('play').bind('play', function () {
        $("#video").trigger('pause');
    });
    $("#teachVideo").unbind('ended').bind('ended', function () {
        $("#video").trigger("play");
    });
    /**
     * 备课教案视频结束
     */
    //    let cacheTimer=setInterval(() => {
    //        console.log(video[0].buffered.end(0),video[0].currentTime);
    //        if (video[0].buffered.end(0) < video[0].currentTime) {
    //            console.log(111);
    //        }else if (video[0].buffered.end(0) == video[0].duration) {
    //            console.log("加载完成");
    //            clearInterval(cacheTimer);
    //        }
    //    }, 500);
})